import { pathToRegexp } from 'path-to-regexp';

const TOKEN_CACHE_KEY = 'dqtoken';

export function getAuthority() {
  const auth = getToken();
  return auth.length > 0 ? 'admin' : '';
}
export function setAuthority(authority) {
  return localStorage.setItem('antd-pro-authority', authority);
}

export function getToken() {
  return localStorage.getItem(TOKEN_CACHE_KEY) || '';
}

export function getFanRuanSsoToken() {
  return localStorage.getItem('frtoken') || '';
}

export function setFanRuanSsoToken(authority) {
  return localStorage.setItem('frtoken', authority);
}

export function setToken(token) {
  document.cookie = `logintoken=${token};path=/`;
  return localStorage.setItem(TOKEN_CACHE_KEY, token);
}

export const getAuthorityFromRoutes = (routes = [], path = '') => {
  const pathname = path.replace('#', '');
  if (pathname === '/personal') return ['admin'];
  const isComponent = routes.some(
    ({ component }) => component && pathToRegexp(`/${component}`).exec(pathname),
  );
  const authority = isComponent ? ['admin'] : [];
  return authority;
};
